<template>
  <view class="membership-plans">
    <!-- 套餐类型切换 -->
    <view class="plans-header">
      <view 
        v-for="(tab, index) in planTabs" 
        :key="index"
        :class="['tab-item', currentTab === index ? 'active' : '']"
        @tap="switchTab(index)"
      >
        {{ tab }}
      </view>
    </view>

    <!-- 套餐列表 -->
    <swiper class="plans-swiper" :current="currentTab" @change="onSwiperChange">
      <!-- 普通会员套餐 -->
      <swiper-item>
        <scroll-view scroll-y class="plans-scroll">
          <view class="plans-grid">
            <view 
              v-for="(plan, index) in standardPlans" 
              :key="index"
              :class="['plan-card', selectedPlanId === plan.id ? 'selected' : '']"
              @tap="selectPlan(plan)"
            >
              <!-- 套餐标题 -->
              <view class="plan-header">
                <text class="plan-name">{{ plan.name }}</text>
                <text class="plan-badge" v-if="plan.badge">{{ plan.badge }}</text>
              </view>

              <!-- 价格信息 -->
              <view class="plan-price">
                <text class="price-currency">¥</text>
                <text class="price-value">{{ getPlanPrice(plan) }}</text>
                <text class="price-period">/{{ getPlanPeriod(plan) }}</text>
              </view>

              <!-- 优惠标签 -->
              <text class="discount-tag" v-if="plan.discount">{{ plan.discount }}</text>

              <!-- 套餐特权 -->  
              <view class="plan-features">
                <view class="feature-item">
                  <text class="feature-icon">✓</text>
                  <text class="feature-text">{{ formatNumber(plan.dailyTokenLimit) }}Token/天</text>
                </view>
                <view class="feature-item">
                  <text class="feature-icon">✓</text>
                  <text class="feature-text">{{ plan.chatLimit }}次对话/天</text>
                </view>
                <view class="feature-item">
                  <text class="feature-icon">✓</text>
                  <text class="feature-text">{{ plan.switchAgentLimit }}次切换/天</text>
                </view>
              </view>

              <!-- 购买按钮 -->
              <button class="buy-btn" @tap.stop="buyPlan(plan)">
                立即开通
              </button>
            </view>
          </view>
        </scroll-view>
      </swiper-item>

      <!-- 临时卡套餐 -->
      <swiper-item>
        <scroll-view scroll-y class="plans-scroll">
          <view class="plans-grid">
            <view 
              v-for="(plan, index) in tempPlans" 
              :key="index"
              :class="['plan-card', selectedPlanId === plan.id ? 'selected' : '']"
              @tap="selectPlan(plan)"
            >
              <view class="plan-header">
                <text class="plan-name">{{ plan.name }}</text>
                <text class="plan-badge" v-if="plan.badge">{{ plan.badge }}</text>
              </view>

              <view class="plan-price">
                <text class="price-currency">¥</text>
                <text class="price-value">{{ getPlanPrice(plan) }}</text>
                <text class="price-period">/{{ plan.days }}天</text>
              </view>

              <view class="plan-features">
                <view class="feature-item">
                  <text class="feature-icon">✓</text>
                  <text class="feature-text">{{ formatNumber(plan.dailyTokenLimit) }}Token</text>
                </view>
                <view class="feature-item">
                  <text class="feature-icon">✓</text>
                  <text class="feature-text">{{ plan.chatLimit }}次对话</text>
                </view>
                <view class="feature-item">
                  <text class="feature-icon">✓</text>
                  <text class="feature-text">{{ plan.switchAgentLimit }}次切换</text>
                </view>
              </view>

              <button class="buy-btn" @tap.stop="buyPlan(plan)">
                立即购买
              </button>
            </view>
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>

    <!-- 支付弹窗 -->
    <view class="payment-modal" v-if="showPayment">
      <view class="modal-mask" @tap="closePayment"></view>
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">确认订单</text>
          <text class="modal-close" @tap="closePayment">×</text>
        </view>

        <view class="modal-body">
          <view class="order-item">
            <text class="item-label">商品名称</text>
            <text class="item-value">{{ selectedPlan?.name }}</text>
          </view>
          <view class="order-item">
            <text class="item-label">订阅类型</text>
            <text class="item-value">{{ getSubscriptionTypeText(selectedSubscriptionType) }}</text>
          </view>
          <view class="order-item highlight">
            <text class="item-label">支付金额</text>
            <text class="item-value price">¥{{ selectedPlanPrice }}</text>
          </view>
        </view>

        <view class="modal-footer">
          <button 
            class="confirm-btn"
            :disabled="isPayLoading"
            :loading="isPayLoading"
            @tap="confirmPayment"
          >
            确认支付
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useMembershipStore } from '@/stores'

const props = defineProps({
  plans: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['buy'])

const membershipStore = useMembershipStore()

// 状态数据
const currentTab = ref(0)
const selectedPlanId = ref(null)
const selectedPlan = ref(null)
const selectedSubscriptionType = ref('MONTHLY')
const selectedPlanPrice = ref('0.00')
const showPayment = ref(false)
const isPayLoading = ref(false)

// 套餐类型
const planTabs = ['套餐会员', '临时卡']

// 普通会员套餐
const standardPlans = computed(() => {
  return props.plans.filter(plan => plan.code !== 'TEMP')
})

// 临时卡套餐
const tempPlans = computed(() => {
  return props.plans.filter(plan => plan.code === 'TEMP')
})

// 切换套餐类型
const switchTab = (index) => {
  currentTab.value = index
  selectedPlanId.value = null
  selectedPlan.value = null
  selectedSubscriptionType.value = currentTab.value === 0 ? 'MONTHLY' : 'TEMP'
}

// 轮播切换
const onSwiperChange = (e) => {
  currentTab.value = e.detail.current
}

// 选择套餐
const selectPlan = (plan) => {
  selectedPlanId.value = plan.id
  selectedPlan.value = plan
  calculatePrice()
}

// 计算价格
const calculatePrice = () => {
  if (!selectedPlan.value) {
    selectedPlanPrice.value = '0.00'
    return
  }

  const plan = selectedPlan.value
  let price = 0

  if (plan.code === 'TEMP') {
    price = plan.subscriptionOptions[0].price
  } else {
    const option = plan.subscriptionOptions.find(
      opt => opt.type === selectedSubscriptionType.value
    )
    price = option ? option.price : 0
  }

  selectedPlanPrice.value = price.toFixed(2)
}

// 购买套餐
const buyPlan = (plan) => {
  selectedPlan.value = plan
  calculatePrice()
  showPayment.value = true
}

// 关闭支付弹窗
const closePayment = () => {
  showPayment.value = false
}

// 确认支付
const confirmPayment = async () => {
  if (isPayLoading.value) return

  try {
    isPayLoading.value = true

    // 创建订阅订单
    const orderParams = {
      levelId: selectedPlan.value.id,
      subscriptionType: selectedSubscriptionType.value 
    }

    const res = await membershipStore.createSubscription(orderParams)

    if (res) {
      // 关闭弹窗
      closePayment()
      // 跳转支付页面
      uni.navigateTo({
        url: `/pages/payment/index?orderId=${res.orderId}&amount=${selectedPlanPrice.value}&type=vip`
      })
    }
  } catch (error) {
    console.error('创建订单失败:', error)
  } finally {
    isPayLoading.value = false
  }
}

// 获取套餐价格
const getPlanPrice = (plan) => {
  if (!plan.subscriptionOptions || plan.subscriptionOptions.length === 0) {
    return '0.00'
  }
  return plan.subscriptionOptions[0].price
}

// 获取套餐周期
const getPlanPeriod = (plan) => {
  if (plan.code === 'TEMP') {
    return plan.days + '天'
  }

  switch (selectedSubscriptionType.value) {
    case 'MONTHLY':
      return '月'
    case 'QUARTERLY':
      return '季'
    case 'YEARLY':
      return '年'
    default:
      return '未知'
  }
}

// 获取订阅类型文本
const getSubscriptionTypeText = (type) => {
  switch (type) {
    case 'MONTHLY':
      return '月卡'
    case 'QUARTERLY':
      return '季卡'
    case 'YEARLY':
      return '年卡'
    case 'TEMP':
      return '临时卡'
    default:
      return '未知'
  }
}

// 格式化数字
const formatNumber = (num) => {
  return String(num).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
</script>

<style lang="scss">
.membership-plans {
  .plans-header {
    display: flex;
    margin-bottom: 30rpx;
    background: #fff;
    border-radius: 12rpx;
    padding: 20rpx;

    .tab-item {
      flex: 1;
      text-align: center;
      font-size: 28rpx;
      color: #666;
      padding: 16rpx 0;
      position: relative;

      &.active {
        color: #5677fc;
        
        &:after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 25%;
          width: 50%;
          height: 4rpx;
          background: #5677fc;
          border-radius: 2rpx;
        }
      }
    }
  }

  .plans-swiper {
    height: 900rpx;
  }

  .plans-scroll {
    height: 100%;
  }

  .plans-grid {
    display: flex;
    flex-wrap: wrap;
    padding: 20rpx;
  }

  .plan-card {
    &.selected {
      border: 2rpx solid #5677fc;
      transform: scale(1.02);
    }
  
    .plan-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
  
      .plan-name {
        font-size: 32rpx;
        color: #333;
        font-weight: 600;
      }
  
      .plan-badge {
        font-size: 22rpx;
        color: #5677fc;
        background: rgba(86, 119, 252, 0.1);
        padding: 4rpx 12rpx;
        border-radius: 20rpx;
      }
    }
  
    .plan-price {
      margin-bottom: 20rpx;
      
      .price-currency {
        font-size: 28rpx;
        color: #ff4d4f;
      }
  
      .price-value {
        font-size: 48rpx;
        color: #ff4d4f;
        font-weight: 600;
        margin: 0 4rpx;
      }
  
      .price-period {
        font-size: 24rpx;
        color: #999;
      }
    }
  
    .discount-tag {
      display: inline-block;
      font-size: 22rpx;
      color: #ff4d4f;
      background: rgba(255, 77, 79, 0.1);
      padding: 4rpx 12rpx;
      border-radius: 20rpx;
      margin-bottom: 20rpx;
    }
  
    .plan-features {
      margin-bottom: 30rpx;
  
      .feature-item {
        display: flex;
        align-items: center;
        margin-bottom: 12rpx;
  
        &:last-child {
          margin-bottom: 0;
        }
  
        .feature-icon {
          color: #52c41a;
          font-size: 24rpx;
          margin-right: 8rpx;
        }
  
        .feature-text {
          font-size: 24rpx;
          color: #666;
        }
      }
    }
  
    .buy-btn {
      width: 100%;
      height: 80rpx;
      line-height: 80rpx;
      background: #5677fc;
      color: #fff;
      font-size: 28rpx;
      border-radius: 40rpx;
      text-align: center;
      margin-top: 20rpx;
  
      &:active {
        opacity: 0.9;
      }
    }
  }
  
  .payment-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
  
    .modal-mask {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.6);
    }
  
    .modal-content {
      position: absolute;
      left: 50rpx;
      right: 50rpx;
      bottom: 100rpx;
      background: #fff;
      border-radius: 20rpx;
      padding: 30rpx;
  
      .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30rpx;
  
        .modal-title {
          font-size: 32rpx;
          color: #333;
          font-weight: 600;
        }
  
        .modal-close {
          font-size: 40rpx;
          color: #999;
          padding: 10rpx;
        }
      }
  
      .modal-body {
        .order-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20rpx;
  
          .item-label {
            font-size: 28rpx;
            color: #666;
          }
  
          .item-value {
            font-size: 28rpx;
            color: #333;
  
            &.price {
              font-size: 36rpx;
              color: #ff4d4f;
              font-weight: 600;
            }
          }
  
          &.highlight {
            margin: 30rpx 0;
            padding: 20rpx 0;
            border-top: 1px dashed #eee;
            border-bottom: 1px dashed #eee;
          }
        }
      }
  
      .modal-footer {
        margin-top: 30rpx;
  
        .confirm-btn {
          width: 100%;
          height: 88rpx;
          line-height: 88rpx;
          background: #5677fc;
          color: #fff;
          font-size: 32rpx;
          border-radius: 44rpx;
          text-align: center;
  
          &:active {
            opacity: 0.9;
          }
  
          &:disabled {
            opacity: 0.6;
          }
        }
      }
    }
  }